import logging
import sys
import os
from logging.handlers import RotatingFileHandler

def setup_logging():
    """设置日志配置"""
    # 创建日志目录
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 配置日志格式
    log_format = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # 创建 logger
    logger = logging.getLogger("mcp_market")
    logger.setLevel(logging.INFO)

    # 创建控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(log_format)
    logger.addHandler(console_handler)

    # 创建文件处理器
    file_handler = RotatingFileHandler(
        os.path.join(log_dir, "app.log"),
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5
    )
    file_handler.setFormatter(log_format)
    logger.addHandler(file_handler)

    # 防止日志重复
    logger.propagate = False

    # 设置第三方库日志级别
    logging.getLogger('uvicorn').setLevel(logging.INFO)
    logging.getLogger('uvicorn.access').setLevel(logging.INFO)
    logging.getLogger('sqlalchemy').setLevel(logging.WARNING)
    logging.getLogger('httpx').setLevel(logging.INFO)

    # 设置MCP相关模块的日志级别为DEBUG
    # 创建一个特定的MCP日志记录器命名空间
    mcp_logger = logging.getLogger('mcp')
    mcp_logger.setLevel(logging.DEBUG)

    # 为特定服务设置日志级别
    for logger_name in [
        'app.services.mcp_client',
        'app.services.mcp_client_service',
        'app.services.mcp_tool',
        'backend.app.services.mcp_client',
        'backend.app.services.mcp_client_service',
        'backend.app.services.mcp_tool',
        'app.api.api_v1.endpoints.tools',
        'backend.app.api.api_v1.endpoints.tools'
    ]:
        logging.getLogger(logger_name).setLevel(logging.DEBUG)

    return logger

# 创建全局 logger 对象
logger = setup_logging()

# 导出 logger 对象和 setup_logging 函数
__all__ = ['logger', 'setup_logging'] 